package dbtools;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;

public class DBOperate {

	private Context context;

	public DBOperate(Context context) {
		super();
		this.context = context;
	}

	private ContentValues getContentValuesFromHashMap(HashMap valueMap) {
		ContentValues returnContentValuesRef = new ContentValues();
		Iterator iterator = valueMap.keySet().iterator();
		while (iterator.hasNext()) {
			String key = "" + iterator.next();
			String value = "" + valueMap.get(key);
			returnContentValuesRef.put(key, value);
		}
		return returnContentValuesRef;
	}

	public long insert(String tableName, HashMap valueMap)
			throws SQLiteException {
		SQLiteDatabase dataBaseRef = GetDataBase.getDataBase(context);
		return dataBaseRef.insertOrThrow(tableName, "",
				getContentValuesFromHashMap(valueMap));
	}

	public long delete(String tableName, String where, String[] whereValue)
			throws SQLiteException {
		SQLiteDatabase dataBaseRef = GetDataBase.getDataBase(context);
		return dataBaseRef.delete(tableName, where, whereValue);
	}

	public long update(String tableName, HashMap valueMap, String where,
			String[] whereValue) throws SQLiteException {
		SQLiteDatabase dataBaseRef = GetDataBase.getDataBase(context);
		return dataBaseRef.update(tableName,
				getContentValuesFromHashMap(valueMap), where, whereValue);
	}

	public List select(String sql, String[] selectValue) throws SQLiteException {
		ArrayList returnList = new ArrayList();

		SQLiteDatabase dataBaseRef = GetDataBase.getDataBase(context);
		Cursor cursorRef = dataBaseRef.rawQuery(sql, selectValue);

		while (cursorRef.moveToNext()) {
			HashMap rowMap = new HashMap();
			int selectColCount = cursorRef.getColumnCount();
			for (int i = 0; i < selectColCount; i++) {
				String[] colName = cursorRef.getColumnNames();
				for (int j = 0; j < colName.length; j++) {
					int colIndex = cursorRef.getColumnIndex(colName[j]);
					String colValue = cursorRef.getString(colIndex);
					rowMap.put(colName[j], colValue);
				}
			}
			returnList.add(rowMap);
		}

		return returnList;
	}

}
